import { Request, toast, getDate } from '../../../utils/util.js'
let request = new Request()
let app = getApp()
Page({
  data: {
    today : '',
    tomorrow : '',
    goods : null,
    formData : {
      chatType : 5,
      id : '',
      stock : '',
      bargain_price : 0,
      start_time : '',
      end_time : '',
      expire : ''
    }
  },

  input(e) {
    let target = e.currentTarget.dataset.target
    let update = {}
    update['formData.' + target] = e.detail.value
    this.setData(update)
  },

  confirmGoods (goods) {
    this.setData({ goods: goods, 'formData.id' : goods.id})
  },

  confirm () {
    let formData = this.data.formData

    if (!formData.id){
      toast('请选择商品')
      return
    }

    if (formData.stock === '') {
      toast('请输入库存数')
      return
    }

    if (formData.stock < 1) {
      toast('库存数不能少于1')
      return
    }

    if (formData.bargain_price === '') {
      toast('请输入底价')
      return
    }

    if (formData.bargain_price < 0) {
      toast('红包数量不能小于0')
      return
    }

    if (formData.start_time === '') {
      toast('请选择活动开始时间')
      return
    }

    if (formData.end_time === '') {
      toast('请选择活动结束时间')
      return
    }

    if (formData.expire === '') {
      toast('请填写砍价有效期')
      return
    }

    if (formData.expire < 0.5) {
      toast('红包数量不能小于0.5小时')
      return
    }

    request.post('publish', res => {
      if (res.success) {
        toast('发布成功')
        app.newPublish = true
        wx.navigateBack({
          delta: 3
        })
      } else {
        toast(res.msg)
      }
    }, formData)
  },

  onLoad: function (options) {
    let today = getDate()
    let tomorrow = getDate(1)
    this.setData({ today: today, tomorrow: tomorrow})
  }
})